package com.tutu.mybatis.dynamic.datasource.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.mybatis.dynamic.datasource.annotation.DynamicDatasource;
import com.tutu.mybatis.dynamic.datasource.bean.Balance;
import com.tutu.mybatis.dynamic.datasource.bean.Order;
import com.tutu.mybatis.dynamic.datasource.mapper.OrderMapper;
import com.tutu.mybatis.dynamic.datasource.service.BalanceService;
import com.tutu.mybatis.dynamic.datasource.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author qyy
 * @date 2021/3/18 16:56
 */
@Service
@DynamicDatasource
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    @Resource
    BalanceService balanceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(Order order) {
        Balance balance = balanceService.getById(1);
        logger.info("balance:{}", balance);
        balance.setNum(balance.getNum() + 1);
        balanceService.updateById(balance);
        order.setUserId(balance.getUserId());
        order.setNum(balance.getNum() + order.getNum());
        boolean flag = super.save(order);
        if (flag) {
            throw new RuntimeException("手动异常");
        }
        return false;
    }
}
